package week_04;

import java.util.Comparator;
import java.util.PriorityQueue;

public class MergeKLists_Deque_23 {
    public ListNode mergeKLists(ListNode[] lists) {
        int k = lists.length;
        // 建一个小根堆 ——PriorityDeque
        PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });
        // k 个list头 结果循环入对列
        for (int i = 0; i < k; i++) {
            if (lists[i] != null) {
                queue.offer(lists[i]);
            }
        }

        ListNode head = new ListNode();
        ListNode tail = head;
        while (!queue.isEmpty()) {
            // deque pop 一个 后续一个值入队列
            ListNode cur = queue.poll();
            tail.next = cur;
            tail = tail.next;
            if (cur.next != null) {
                queue.offer(cur.next);
            }
        }
        return head.next;
    }
}
